package com.example.dell.case02_16110100415;

import android.content.Context;
import android.content.Intent;
import android.content.SharedPreferences;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.view.View;
import android.widget.Button;
import android.widget.CheckBox;
import android.widget.EditText;
import android.widget.Toast;

import com.example.dell.case02_16110100415.Bean.ErrorBean;
import com.example.dell.case02_16110100415.Bean.LoginBean;
import com.example.dell.case02_16110100415.Retrofit.RetrofitService;

import java.io.IOException;

import okhttp3.ResponseBody;
import retrofit2.Call;
import retrofit2.Response;
import retrofit2.Retrofit;

public class SignInActivity extends AppCompatActivity {
    private EditText username, password;
    private CheckBox remember;
    private Button sign_in, sign_up;

    private SharedPreferences sharedPreferences;

    private final int MODE = Context.MODE_PRIVATE;

    private final String FILE_NAME = "zyfypt";
    private final String KEY_ID = "id";
    private final String KEY_USERNAME  = "username";
    private final String KEY_PASSWORD = "password";
    private final String KEY_REALNAME = "real_name";
    private final String KEY_SESSION_ID = "session_id";
    private final String KEY_ROLE = "role";
    private final String KEY_SEX = "sex";



    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_sign_in);

        init();

        //读取保存的用户名 密码

        sharedPreferences = getSharedPreferences(FILE_NAME, MODE);

        String savedUserName =
                sharedPreferences.getString(KEY_USERNAME,"");

        String savedPassword =
                sharedPreferences.getString(KEY_PASSWORD, "");

        if (!savedUserName.equals("")
                &&!savedPassword.equals(""))
        {
            //登陆的过程
            username.setText(savedUserName);
            password.setText(savedPassword);
            remember.setChecked(true);

        }

        boolean logout = getIntent().getBooleanExtra("logout",false);

        if (logout){
            username.setText("");
            password.setText("");
        }
    }


    private void login(String username,
                       final String password){

        if (!username.equals("")
                &&!password.equals("")){

            Retrofit retrofit = new Retrofit
                    .Builder()
                    .baseUrl("http://172.24.10.175:8080/foodService/userLogin.do  ")
                    .build();


            RetrofitService retrofitLogin = retrofit.create(RetrofitService.class);


            Call<ResponseBody> call = retrofitLogin.login(username , password);


            call.enqueue(new retrofit2.Callback<ResponseBody>() {

                @Override
                public void onResponse(Call<ResponseBody> call,
                                       Response<ResponseBody> response) {


                    try {

                        byte[] data = response.body().bytes();

                        String text = new String(data);

                        ObjectMapper objectMapper = new ObjectMapper();
                        LoginBean loginBean = objectMapper.readValue(text, LoginBean.class);
                        if (loginBean != null){

                            boolean isRemember =
                                    remember.isChecked();
                            if(isRemember){
                                SharedPreferences.Editor editor =
                                        sharedPreferences.edit();

                                editor.putString(KEY_ID, loginBean.getId());
                                editor.putString(KEY_USERNAME, loginBean.getUsername());
                                editor.putString(KEY_PASSWORD, password);
                                editor.putString(KEY_SESSION_ID, loginBean.getSessionid());
                                editor.putString(KEY_REALNAME, loginBean.getRealname());
                                editor.putString(KEY_ROLE, loginBean.getRolename());
                                editor.putString(KEY_SEX, loginBean.getSex());

                                editor.commit();      //保存数据
                            }
//                            String text_id = loginBean.getId();
//                            String text_username = loginBean.getUsername();
//                            String text_session_id = loginBean.getSessionid();
//                            String text_role = loginBean.getRolename();

                            Toast.makeText(SignInActivity.this, "success", Toast.LENGTH_SHORT).show();
                            finish();
                            Intent intent = new Intent(SignInActivity.
                                    this, MainActivity.class);

                            intent.putExtra("id",loginBean.getId());
                            intent.putExtra("username", loginBean.getUsername());
                            intent.putExtra("real_name", loginBean.getRealname());
                            intent.putExtra("session_id", loginBean.getSessionid());
                            intent.putExtra("role", loginBean.getRolename());




                            startActivity(intent);

                        }else{

                            ErrorBean errorBean = objectMapper.readValue(text, ErrorBean.class);
                            if (errorBean != null){

                                Toast.makeText(SignInActivity.this, errorBean.getError(), Toast.LENGTH_SHORT).show();
                            }
                        }



                    }

                    catch (IOException e) {
                        e.printStackTrace();
                    }
                }

                @Override
                public void onFailure(Call<ResponseBody> call, Throwable t) {

                }
            });

        }else {
            Toast.makeText(this,
                    "pls input the username or password", Toast.LENGTH_SHORT).show();
        }

    }


    private void init(){
        username = findViewById(R.id.username);
        password = findViewById(R.id.password);
        remember = findViewById(R.id.remember);
        sign_in = findViewById(R.id.sign_in);
        sign_up = findViewById(R.id.sign_up);

        sign_in.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                String name = username.getText().toString();
                String pass = password.getText().toString();

                login(name, pass);


//                if(name.equals("123")
//                        && pass.equals("123")){
//                    Intent intent
//                            = new Intent(MainActivity.this,Main2Activity.class);
//                    startActivity(intent);
//                }
//                else{
//
//                    Toast.makeText(MainActivity.this,"username or password was wrong",Toast.LENGTH_SHORT).show();
//                }

            }
        });

//        sign_up.setOnClickListener(new View.OnClickListener() {
//            @Override
//            public void onClick(View v) {
//                Intent intent = new Intent();
//
//                intent.setClass( MainActivity.this,
//                        SignUpActivity.class );
//                startActivity(intent);
//
//            }
//        });

        sign_up.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {

                //启动新页面
                //启动Activity
//                /*
//                 *
//                 * 俩种启动方式：显式启动/隐式启动
//                 *     -无返回数据
//                 *     -有返回数据
//                 *
//                 * */
//                /*
//                 * 3种
//                 * 1)action
//                 * 2)category
//                 * 3)data
//                 * */

                Intent intent = new Intent();
                intent.setAction("demo.ACTION");

                //传递数据
//                intent.putExtra("msg","hello");
//                intent.putExtra("number",100);

                startActivity(intent);
            }
        });



    }

}



